//
//  XJ_QuxianViewController.m
//  XunJieProject
//
//  Created by xue on 2018/6/20.
//  Copyright © 2018年 Soowin. All rights reserved.
//

#import "XJ_QuxianViewController.h"
#import "XJ_ShoukuanViewController.h"
#import "XJ_MoneyCollectModel.h"
#import "XJ_SelectBandView.h"
#import "XJ_SelectFeiLvView.h"
#import "XJ_CreditCardBindViewController.h"
#import "XJ_AddCreditCardViewController.h"
#import "ZDXTabBarControllerViewController.h"

@interface XJ_QuxianViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *up_scrollView;
@property (weak, nonatomic) IBOutlet UIView *timeView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *height_timeView;

@property (weak, nonatomic) IBOutlet ZDXXibLabel *moneyLabel1;
@property (weak, nonatomic) IBOutlet UILabel *moneyLabel2;
@property (weak, nonatomic) IBOutlet UITextField *moneyTF;
@property (weak, nonatomic) IBOutlet ZDXXibLabel *collectMoneyLabel;
@property (weak, nonatomic) IBOutlet UITextField *creditCardTF;
@property (weak, nonatomic) IBOutlet UITextField *depositCardTF;
@property (weak, nonatomic) IBOutlet UILabel *collectPlansLabel;
@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UILabel *creditCardLabel;
@property (weak, nonatomic) IBOutlet UILabel *depositCardLabel;

@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UIButton *shouqianBtn;
@property (weak, nonatomic) IBOutlet UILabel *tishiLbael;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *height_phoneView;

@property (nonatomic,strong) XJ_MoneyCollectModel *model;
@property (nonatomic,strong) XJ_CollectPlansModel *CollectPlans_model;
@property (nonatomic,strong) XJ_CreditCardModel *CreditCard_model;
@property (nonatomic,strong) XJ_DepositCardModel *DepositCard_model;
@property (assign, nonatomic) BOOL isHaveDian;

@end

@implementation XJ_QuxianViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
   
}
- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    self.moneyTF.text =@"";
    self.creditCardTF.text =@"";
    self.depositCardTF.text =@"";
    [self loadMoneycollect];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    
    
    BOOL isBetweenTime =[XJ_QuxianViewController isBetweenFromHour:0 FromMinute:30 toHour:22 toMinute:15];
    if (isBetweenTime) {
        _height_timeView.constant =0;
//        [_shouqianBtn setBackgroundImage:[UIImage imageNamed:@"btn_bg"] forState:UIControlStateNormal];
        _shouqianBtn.backgroundColor =Color_ZhuSeDiao;
        _shouqianBtn.userInteractionEnabled =YES;
    }else{
        _height_timeView.constant =40;
//        [_shouqianBtn setBackgroundImage:nil forState:UIControlStateNormal];
        _shouqianBtn.backgroundColor =[UIColor lightGrayColor];
        _shouqianBtn.userInteractionEnabled =NO;
    }
}

-(void)creatMainUI{
    
    self.nav_titleLabel.text =@"取现";
    _phoneTF.keyboardType =UIKeyboardTypeNumberPad;
    _moneyTF.delegate =self;
    _moneyTF.keyboardType =UIKeyboardTypeDecimalPad;
    _up_scrollView.constant =SafeAreaTopHeight;
    
    _timeLabel.textColor =UIColorFromRGB(0xF39A9A);
    _timeView.backgroundColor =UIColorFromRGB(0xFFCCCC);
    _shouqianBtn.layer.cornerRadius =CGRectGetHeight(_shouqianBtn.frame)/2;
    _shouqianBtn.layer.masksToBounds =YES;
    
    _moneyLabel1.textColor =UIColorFromRGB(0x666666);
    _moneyLabel2.textColor =UIColorFromRGB(0xaaaaaa);
    
    _collectMoneyLabel.textColor =UIColorFromRGB(0xaaaaaa);
    _collectPlansLabel.textColor =UIColorFromRGB(0xe2203f);
    
    
    _creditCardLabel.textColor =UIColorFromRGB(0x666666);
    _depositCardLabel.textColor =UIColorFromRGB(0x666666);
    _creditCardTF.textColor =UIColorFromRGB(0x000000);
    _depositCardTF.textColor =UIColorFromRGB(0x000000);
    
    _tishiLbael.textColor =UIColorFromRGB(0xe2203f);
    
}
- (IBAction)Click_btn:(id)sender {
    
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0://收钱
        {
            CGFloat money =[_moneyTF.text floatValue];
            if (_moneyTF.text.length==0||money==0) {
                [XJ_Utils alertViewWithMessage:@"金额不能小于0"];
                
                return;
            }
            if (money>0&&money<500) {
                [XJ_Utils alertViewWithMessage:@"收款金额不能小于500元"];
                
                return;
            }
            if (money>20000) {
                [XJ_Utils alertViewWithMessage:@"收款金额不能超过20000元"];
                
                return;
            }
            if (_creditCardTF.text.length==0) {
                [XJ_Utils alertViewWithMessage:@"请先绑定信用卡"];
                
                return;
            }
            if (_depositCardTF.text.length==0) {
                [XJ_Utils alertViewWithMessage:@"请选择到账储蓄卡"];
                
                return;
            }
            
            if ([self.model.channelId isEqualToString:@"1"]||[self.model.channelId isEqualToString:@"2"]) {
                if (_phoneTF.text.length==0) {
                    [XJ_Utils alertViewWithMessage:@"请输入手机号码"];
                    
                    return;
                }
                
                
                if ([self.CreditCard_model.feiFanBindFlag integerValue]==0) {//未绑定非凡
                    
                    ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"信用卡实名绑定" image:@"pop_msg_tip_xs"];
                    [alext showXLAlertView];
                    
                    
                    XJ_CreditCardBindViewController *bind =[[XJ_CreditCardBindViewController alloc]init];
                    bind.urlString =self.CreditCard_model.feiFanH5Url;
                    bind.navTitleString =@"信用卡绑定";
                    [self.navigationController pushViewController:bind animated:YES];
                    
                    return;
                }
                
                
                
                
                XJ_ShoukuanViewController *shoukuan =[[XJ_ShoukuanViewController alloc]init];
                shoukuan.collectMoney =_moneyTF.text;
                shoukuan.phone =_phoneTF.text;
                shoukuan.model =self.model;
                shoukuan.DepositCard_model =self.DepositCard_model;
                shoukuan.CreditCard_model =self.CreditCard_model;
                [self.navigationController pushViewController:shoukuan animated:YES];
                
                
            }else{
                
                ////渠道3  没有手机号 直接调用接口
                [self loadNoMessageCollectSubmit];
                
                
            }
            
            
        }
            break;
        case 1://收款信用卡
        {
            
            if (self.model.creditCardList.count>0) {
                XJ_SelectBandView *alext =[[XJ_SelectBandView alloc]initWithTitle:@"信用卡" cellType:@"1" array:self.model.creditCardList];
                alext.block = ^(id selectValue,id selectValueId ) {
                    
                    
                    
//                    if ([self.CreditCard_model.feiFanBindFlag integerValue]==0) {//未绑定非凡
//                        XJ_CreditCardBindViewController *bind =[[XJ_CreditCardBindViewController alloc]init];
//                        [self.navigationController pushViewController:bind animated:YES];
//                    }else{
                        self.CreditCard_model =selectValue;
                        self.creditCardTF.text =[NSString stringWithFormat:@"%@(%@)",self.CreditCard_model.bank,self.CreditCard_model.cardNoTail];
//                    }
                    
                };
                [alext showXLAlertView];
            }else{
//                [XJ_Utils alertViewWithMessage:@"请先绑定信用卡"];

                
                XJ_AddCreditCardViewController *addCreditCardVC =[[XJ_AddCreditCardViewController alloc]init];
                
                addCreditCardVC.userName = self.userInfoModel.userName;
                addCreditCardVC.userIDNumber = self.userInfoModel.idNumber;
                
                [self.navigationController pushViewController:addCreditCardVC animated:YES];
                
            }
            
        }
            break;
        case 2://到账储蓄卡
        {
            XJ_SelectBandView *alext =[[XJ_SelectBandView alloc]initWithTitle:@"储蓄卡" cellType:@"2" array:self.model.depositCardList];
            alext.block = ^(id selectValue,id selectValueId ) {
                
                self.DepositCard_model =selectValue;
                self.depositCardTF.text =[NSString stringWithFormat:@"%@(%@)",self.DepositCard_model.bank,self.DepositCard_model.cardNoTail];
                
            };
            [alext showXLAlertView];
        }
            break;
        case 3://费率
        {
            XJ_SelectFeiLvView *alextView =[[XJ_SelectFeiLvView alloc]initWithTitle:@"选择费率" array:self.model.collectPlans momey:_moneyTF.text];
            alextView.block = ^(XJ_CollectPlansModel* selectValue,NSString *selectMoney) {
                self.CollectPlans_model =selectValue;
                self.collectPlansLabel.text =selectMoney;
            };
            [alextView showXLAlertView];
        }
            break;
        default:
            break;
    }
}

#pragma mark--获取收钱收钱页面数据
-(void)loadMoneycollect{
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:USERID forKey:@"userId"];
    [dic setValue:token forKey:@"token"];
    [XJ_Utils signPost:@"/money/collect?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        
        NSDictionary * dataDic = [jsonObject objectForKey:@"data"];
        XJ_MoneyCollectModel * MoneyCollectModel = [XJ_MoneyCollectModel mj_objectWithKeyValues:dataDic];
        
        self.collectMoneyLabel.text =[NSString stringWithFormat:@"* 收费金额范围 %@元 ~ %@元",MoneyCollectModel.minCollectMoney,MoneyCollectModel.maxCollectMoney];
        
        if ([MoneyCollectModel.channelId isEqualToString:@"3"]) {
            self.height_phoneView.constant =0;
        }else{
            self.height_phoneView.constant =48;
        }
        
        ///取现方案
        NSArray *collectPlans =dataDic[@"collectPlans"];
        NSMutableArray *arr =[[NSMutableArray alloc]init];
        for (NSDictionary *dic in collectPlans) {
            XJ_CollectPlansModel *model =[XJ_CollectPlansModel mj_objectWithKeyValues:dic];
            model.isSelect =NO;
            [arr addObject:model];
        }
        MoneyCollectModel.collectPlans =arr;
        

        
        ////信用卡列表
        NSArray *creditCardList =dataDic[@"creditCardList"];
        NSMutableArray *arr1 =[[NSMutableArray alloc]init];
        for (NSDictionary *dic in creditCardList) {
            XJ_CreditCardModel *model =[XJ_CreditCardModel mj_objectWithKeyValues:dic];
            [arr1 addObject:model];
        }
        MoneyCollectModel.creditCardList =arr1;
        
        ////储蓄卡列表
        NSArray *depositCardList =dataDic[@"depositCardList"];
        NSMutableArray *arr2 =[[NSMutableArray alloc]init];
        for (NSDictionary *dic in depositCardList) {
            XJ_DepositCardModel *model =[XJ_DepositCardModel mj_objectWithKeyValues:dic];
            [arr2 addObject:model];
        }
        MoneyCollectModel.depositCardList =arr2;
        
        self.model =MoneyCollectModel;
        
        
        
        

        
        if (MoneyCollectModel.collectPlans.count>0) {
            XJ_CollectPlansModel *CollectPlans_model =MoneyCollectModel.collectPlans[0];
            CollectPlans_model.isSelect =YES;
            self.CollectPlans_model =CollectPlans_model;
            
            self.collectPlansLabel.text =[NSString stringWithFormat:@"费率:%@%@+%@元，本次手续费:0.0元",CollectPlans_model.rate,@"%",CollectPlans_model.cost];
        }
        
//        if (MoneyCollectModel.creditCardList.count>0) {
//            XJ_CreditCardModel *creditCard_model =MoneyCollectModel.creditCardList[0];
//            self.creditCardTF.text =[NSString stringWithFormat:@"%@(%@)",creditCard_model.bank,creditCard_model.cardNoTail];
//            self.CreditCard_model =creditCard_model;
//        }
        
//        if (MoneyCollectModel.depositCardList.count>0) {
//            XJ_DepositCardModel *depositCard_model =MoneyCollectModel.depositCardList[0];
//            self.depositCardTF.text =[NSString stringWithFormat:@"%@(%@)",depositCard_model.bank,depositCard_model.cardNoTail];
//            self.DepositCard_model =depositCard_model;
//        }
        
//        self.phoneTF.text =MoneyCollectModel.mobile;

        
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}

#pragma mark--渠道3 没有手机验证码收钱确定接口
-(void)loadNoMessageCollectSubmit{
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:USERID forKey:@"userId"];
    [dic setValue:token forKey:@"token"];
    
    [dic setValue:_moneyTF.text forKey:@"collectMoney"];//收款金额
    [dic setValue:_CollectPlans_model.collectPlanId forKey:@"collectPlanId"];//收款方案Id
    [dic setValue:_CreditCard_model.creditCardId forKey:@"creditCardId"];//信用卡Id
    [dic setValue:_CreditCard_model.cardNo forKey:@"creditCardNo"];//信用卡号码
    [dic setValue:_DepositCard_model.depositCardId forKey:@"depositCardId"];//储蓄卡Id
    [dic setValue:_DepositCard_model.cardNo forKey:@"depositCardNo"];//储蓄卡号码
    [dic setValue:self.model.channelId forKey:@"channelId"];//渠道id
    
    
    [XJ_Utils signPost:@"/money/yiBaoCollectSubmit?" parameters:dic success:^(NSInteger recode, id jsonObject) {
    
//        ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"取现成功" image:@"pop_msg_succeed_xs"];
//        [alext showXLAlertView];
        
//        ZDXTabBarControllerViewController *tab =(ZDXTabBarControllerViewController*)KWINDOW.rootViewController;
//        [tab setSelectedIndex:1];
//
//        [self.navigationController popToRootViewControllerAnimated:YES];
        
        
        NSDictionary * dataDic = [jsonObject objectForKey:@"data"];
        NSString *h5Url =nil;
        if ([dataDic.allKeys containsObject:@"h5Url"]) {
            h5Url =dataDic[@"h5Url"];
        }
        XJ_CreditCardBindViewController *bind =[[XJ_CreditCardBindViewController alloc]init];
        bind.urlString =h5Url;
        bind.navTitleString =@"取现";
        [self.navigationController pushViewController:bind animated:YES];
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        
        
        
    }];
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    if ([textField isEqual:_moneyTF]) {
        CGFloat rate =[self.CollectPlans_model.rate floatValue];
        CGFloat cost =[self.CollectPlans_model.cost floatValue];
        CGFloat money =[self.moneyTF.text floatValue];
        CGFloat collectPlans =rate/100*money+cost;
        NSString *collectPlansStr =[NSString stringWithFormat:@"%f",collectPlans];
        
        NSDecimalNumber *subtotal = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@",collectPlansStr]];
        collectPlansStr =[XJ_QuxianViewController notRounding:subtotal afterPoint:1];
        
        self.collectPlansLabel.text =[NSString stringWithFormat:@"费率:%@%@+%@元，本次手续费:%@元",self.CollectPlans_model.rate,@"%",self.CollectPlans_model.cost,collectPlansStr];
    }
}


/**
 *  textField的代理方法，监听textField的文字改变
 *  textField.text是当前输入字符之前的textField中的text
 *
 *  @param textField textField
 *  @param range     当前光标的位置
 *  @param string    当前输入的字符
 *
 *  @return 是否允许改变
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    /*
     * 不能输入.0-9以外的字符。
     * 设置输入框输入的内容格式
     * 只能有一个小数点
     * 小数点后最多能输入两位
     * 如果第一位是.则前面加上0.
     * 如果第一位是0则后面必须输入点，否则不能输入。
     */
    
    // 判断是否有小数点
    if ([textField.text containsString:@"."]) {
        self.isHaveDian = YES;
    }else{
        self.isHaveDian = NO;
    }
    
    if (string.length > 0) {
        
        //当前输入的字符
        unichar single = [string characterAtIndex:0];
        NSLog(@"single = %c",single);
        
        // 不能输入.0-9以外的字符
        if (!((single >= '0' && single <= '9') || single == '.'))
        {
            //            [MBProgressHUD bwm_showTitle:@"您的输入格式不正确" toView:self hideAfter:1.0];
            return NO;
        }
        
        // 只能有一个小数点
        if (self.isHaveDian && single == '.') {
            //            [MBProgressHUD bwm_showTitle:@"最多只能输入一个小数点" toView:self hideAfter:1.0];
            return NO;
        }
        
        // 如果第一位是.则前面加上0.
        if ((textField.text.length == 0) && (single == '.')) {
            textField.text = @"0";
        }
        
        // 如果第一位是0则后面必须输入点，否则不能输入。
        if ([textField.text hasPrefix:@"0"]) {
            if (textField.text.length > 1) {
                NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
                if (![secondStr isEqualToString:@"."]) {
                    //                    [MBProgressHUD bwm_showTitle:@"第二个字符需要是小数点" toView:self hideAfter:1.0];
                    return NO;
                }
            }else{
                if (![string isEqualToString:@"."]) {
                    //                    [MBProgressHUD bwm_showTitle:@"第二个字符需要是小数点" toView:self hideAfter:1.0];
                    return NO;
                }
            }
        }
        
        // 小数点后最多能输入两位
        if (self.isHaveDian) {
            NSRange ran = [textField.text rangeOfString:@"."];
            // 由于range.location是NSUInteger类型的，所以这里不能通过(range.location - ran.location)>2来判断
            if (range.location > ran.location) {
                if ([textField.text pathExtension].length > 1) {
                    //                    [MBProgressHUD bwm_showTitle:@"小数点后最多有两位小数" toView:self hideAfter:1.0];
                    return NO;
                }
            }
        }
        
    }
    
    return YES;
}

/**
 *    @brief    截取指定小数位的值
 *
 *    @param     price     需要转化的数据
 *    @param     position     有效小数位
 *
 *    @return    截取后数据
 */
+ (NSString *)notRounding:(NSDecimalNumber *)price afterPoint:(NSInteger)position
{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundUp scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *roundedOunces;
    roundedOunces = [price decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    
    return [NSString stringWithFormat:@"%@",roundedOunces];
}

/**
 * @brief 判断当前时间是否在fromHour和toHour之间。如，fromHour=8，toHour=23时，即为判断当前时间是否在8:00-23:00之间
 */
+ (BOOL)isBetweenFromHour:(NSInteger)fromHour FromMinute:(NSInteger)fromMin toHour:(NSInteger)toHour toMinute:(NSInteger)toMin
{
    NSDate *date8 = [self getCustomDateWithHour:fromHour andMinute:fromMin];
    NSDate *date23 = [self getCustomDateWithHour:toHour andMinute:toMin];
    
    NSDate *currentDate = [NSDate date];
    
    if ([currentDate compare:date8]==NSOrderedDescending && [currentDate compare:date23]==NSOrderedAscending)
    {
        NSLog(@"该时间在 %ld:%ld-%ld:%ld 之间！", fromHour, fromMin, toHour, toMin);
        return YES;
    }
    return NO;
}

/**
 * @brief 生成当天的某个点（返回的是伦敦时间，可直接与当前时间[NSDate date]比较）
 * @param hour 如hour为“8”，就是上午8:00（本地时间）
 */
+ (NSDate *)getCustomDateWithHour:(NSInteger)hour andMinute:(NSInteger)minute
{
    //获取当前时间
    NSDate *currentDate = [NSDate date];
    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *currentComps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
    
    //设置当天的某个点
    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    [resultComps setYear:[currentComps year]];
    [resultComps setMonth:[currentComps month]];
    [resultComps setDay:[currentComps day]];
    [resultComps setHour:hour];
    [resultComps setMinute:minute];
    
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    return [resultCalendar dateFromComponents:resultComps];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
